home *** CD-ROM | disk | FTP | other *** search
- Path: svnews.ubinet.ubs.com!ubszh!ubszh!jis
- From: jis@ubszh.net.ch (Johnston Ian (by ubsswop))
- Newsgroups: comp.lang.c++
- Subject: Re: [] overload..(newbie in distress)
- Date: 22 Jan 1996 13:59:32 GMT
- Organization: UBS
- Distribution: world
- Message-ID: <4e0584$1k3@ubszh.fh.zh.ubs.com>
- References: <DLGppJ.31C@undergrad.math.uwaterloo.ca> <Robert.Lendvai-2101960118330001@129.170.80.94>
- NNTP-Posting-Host: nol2179.fh.zh.ubs.com
-
- In article <Robert.Lendvai-2101960118330001@129.170.80.94>, Robert.Lendvai@dartmouth.edu (Robert Lendvai) writes:
- |> In article <DLGppJ.31C@undergrad.math.uwaterloo.ca>,
- |> tthiraku@landen.math.uwaterloo.ca (Thanou Thirakul) wrote:
- |>
- |> > Hi..
- |> >
- |> > I'm currently stuck on how to overload [] operator such that
- |> > it does two different tasks..
- |> >
- |> >
- |> > case 1:
- |> >
- |> > // A is an instance of a class that contains a linkist.
- |> >
- |> > A[5] = val; // store val into the fifth node of a linklist.
- |> > val = A[5] ; // returns the value of the fifth node of a linklist.
- |> >
- |> >
- |> > I was wondering how can C++ differentiate these two senerios?
- |> >
- |> > Anything help will greatly appreciated..
- |> >
- |> > Thank You Kindly
- |> > --
- |> > Thanou Thirakul
- |> > tthiraku@undergrad.math.uwaterloo.ca
- |> > http://www.undergrad.math.uwaterloo.ca/~tthiraku
- |> > ___________________________________________________________
- |> > | |
- |> > | <after submitting a CS assignment> |
- |> > | |
- |> > | "Well, that was the most well-documented non-working |
- |> > | piece of code I have ever written.. " -unknown |
- |> > | |
- |> > |___________________________________________________________|
- |>
- |> The = assignment operator can not be overloaded.
-
- The = assignment operator can be overloaded, actually, but that is not
- the answer to this question.
-
- You need to make operator[] return a new object; that new object handles
- operator =() and operator T().
-
- For example, assuming you are storing floats:
-
- class ARef;
-
- class A
- {
- public:
- // Whatever
- ARef operator[](int index);
-
- void putAt(int index, float f)
- {
- // Store f at index.
- }
-
- float getAt(int index)
- {
- // REtrieve float at index.
- }
- };
-
-
- class ARef
- {
- public:
- ARef(A &a, int i)
- : aObj(a),
- index(i)
- {
- }
-
- void operator = (float f)
- {
- aObj.putAt(index, f);
- }
-
- operator float()
- {
- aObj.getAt(index);
- }
-
- private:
- A &aObj;
- int index;
- };
-
-
- ARef A::operator [](int index)
- {
- return ARef(*this, index);
- }
-
-
- Now
-
- a[5] = val;
-
- becomes equivalent to:
-
- ARef tmp = a[5];
- tmp = val; // ARef::operator = (float);
-
- and
-
- val = a[5];
-
- becomes equivalent to:
-
- ARef tmp = a[5];
- val = tmp; // ARef::operator float();
-
-
- Beware of performance implications if you use this in tight loops and
- your compiler does not inline well.
-
- Ian
-